# coding=utf-8
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.webdriver import WebDriver
from selenium.common import NoSuchElementException

from app_auto_po.utils.log_util import logger
from app_auto_po.utils.util import Utils


class BasePage:


    def __init__(self, driver: WebDriver = None):
        self.driver = driver


    # 元素定位
    def _find_ele(self,by,locator):
        ele = self.driver.find_element(by, locator)
        return ele


    # 点击
    def click(self,by,locator):
        ele = self._find_ele(by,locator)
        ele.click()


    # 输入文本
    def input(self,by,locator,text):
        ele = self._find_ele(by, locator)
        ele.click()
        ele.send_keys(text)


    # 获取元素列表
    def get_eles(self,by,locator):
        eles = self.driver.find_elements(by, locator)
        return eles

    # 获取文本
    def get_text(self,by,locator):
        ele = self._find_ele(by, locator)
        text = ele.text
        return text


    # 返回上一页
    def to_back(self):

        self.driver.back()


    # 滑动寻找元素
    def swipe_find_text(self, text, direction, max=5):
        self.driver.implicitly_wait(1)
        for i in range(max):
            try:
                ele = self.driver.find_element(AppiumBy.XPATH, f'//*[@text="{text}"]')
                return ele
            except:
                self.swipe_window(direction)
        self.driver.implicitly_wait(10)
        raise NoSuchElementException(f"滑动之后，未找到 {text} 元素")


    # 向上滑动
    def swipe_window(self, direction):
        size = self.driver.get_window_size()
        width = size.get("width")
        height = size.get("height")
        start_x = width * 0.5
        start_y = height * 0.8
        end_x = start_x
        end_y = height * 0.2
        if direction == "up":
            self.driver.swipe(start_x, start_y, end_x, end_y)
        if direction == "down":
            self.driver.swipe(end_x, end_y, start_x, start_y)

    def screenshot(self):
        '''
        截图
        :param path: 截图保存路径
        '''
        file_path = Utils.save_source_datas("images")
        # 截图
        self.driver.save_screenshot(file_path)
        logger.info(f"截图保存的路径为{file_path}")
        # 返回保存图片的路径
        return file_path

    def save_page_source(self):
        '''
        保存页面源码
        :return: 返回源码文件路径
        '''
        file_path = Utils.save_source_datas("pagesource")
        # 写 page source 文件
        with open(file_path, "w", encoding="u8") as f:
            f.write(self.driver.page_source)
        logger.info(f"源码保存的路径为{file_path}")
        # 返回 page source 保存路径
        return file_path
